import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { hideTabBar: true, requiresGuest: true }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
      meta: { hideTabBar: true, requiresGuest: true }
    },
    {
      path: '/',
      name: 'home',
      component: () => import('../views/HomeView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/upload',
      name: 'upload',
      component: () => import('../views/UploadView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/share',
      name: 'share',
      component: () => import('../views/ShareView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/share/create',
      name: 'shareCreate',
      component: () => import('../views/ShareCreateView.vue'),
      meta: { hideTabBar: true, requiresAuth: true }
    },
    {
      path: '/share/edit/:shareId',
      name: 'shareEdit',
      component: () => import('../views/ShareEditView.vue'),
      meta: { hideTabBar: true, requiresAuth: true }
    },
    {
      path: '/share/:shareCode',
      name: 'shareAccess',
      component: () => import('../views/ShareAccessView.vue'),
      meta: { hideTabBar: true, requiresAuth: false }
    },
    {
      path: '/recycle',
      name: 'recycle',
      component: () => import('../views/RecycleView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('../views/ProfileView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/preview/:fileId',
      name: 'preview',
      component: () => import('../views/PreviewView.vue'),
      meta: { hideTabBar: true, requiresAuth: true }
    },
    {
      path: '/move',
      name: 'move',
      component: () => import('../views/MoveView.vue'),
      meta: { hideTabBar: true, requiresAuth: true }
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/'
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const isAuthenticated = !!token

  if (to.meta.requiresAuth && !isAuthenticated) {
    // 需要登录但未登录，跳转到登录页
    next('/login')
  } else if (to.meta.requiresGuest && isAuthenticated) {
    // 已登录用户访问登录/注册页，跳转到首页
    next('/')
  } else {
    next()
  }
})

export default router
